#include "openglwidget.h"

OpenGLWidget::OpenGLWidget(QWidget *parent)
    : QOpenGLWidget(parent)
{
    qDebug() << "Type: Normal QPainter with OpenGL";
    count = 0;
    time = new QElapsedTimer();
    time->start();
    initializeOriginArraies(5000);
}

OpenGLWidget::~OpenGLWidget()
{
    delete time;
    delete shaderProgram;
    delete []originX;
    delete []originY;
}

void OpenGLWidget::initializeGL()
{
    initializeOpenGLFunctions();
//    shaderProgram = new QOpenGLShaderProgram(this);
//    shaderProgram->addCacheableShaderFromSourceFile(QOpenGLShader::Vertex, ":/Shader/Shader/vShader.vsh");
//    shaderProgram->addCacheableShaderFromSourceFile(QOpenGLShader::Fragment, ":/Shader/Shader/fragShader.fsh");
//    shaderProgram->link();
//    shaderProgram->bind();
}

void OpenGLWidget::paintGL()
{
    QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
    f->glClearColor(0.0, 0.0, 0.0, 1.0);
    f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    time->restart();
    f->glDisable(GL_DEPTH_TEST);
    QPainter painter;
    painter.begin(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::yellow);
    QPainterPath path;
    int height = this->height();
    int width = this->width();
    qreal *tempx = originX;
    qreal *tempy = originY;
    int trap = pointsAmount - 1;
    for(int i = 0; i < pointsAmount; i++) {
        qreal x = (*tempx) * width / trap;
        qreal y = (0.5 - 0.4 * (*tempy)) * height;
        path.lineTo(x, y);
        tempx++; tempy++;
    }
    painter.drawPath(path);
    painter.end();
    f->glEnable(GL_DEPTH_TEST);
    qDebug() << time->nsecsElapsed();
    count++;
    this->setWindowTitle(QString::number(count));
}

void OpenGLWidget::resizeGL(int w, int h)
{
    QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
    f->glViewport(0, 0, w, h);
}

void OpenGLWidget::initializeOriginArraies(int num)
{
    pointsAmount = num;
    if(pointsAmount <= 0) {
        qDebug() << "Invalid Input";
        return;
    } else {
        time->restart();
        originX = new qreal[pointsAmount];
        originY = new qreal[pointsAmount];
        qreal *tempX = originX;
        qreal *tempY = originY;
        for(int i = 0; i < pointsAmount; i++) {
            *tempX = i;
            *tempY = qSin(M_PI / 500 * i);
            tempX++;
            tempY++;
        }
        qDebug() << "Init Time:" << time->nsecsElapsed() << "ns";
    }
}
